//
//  WBNetworkManager.swift
//  Weibo
//
//  Created by yinbo on 2018/3/5.
//  Copyright © 2018年 yinbo. All rights reserved.
//

import UIKit
import AFNetworking
enum WBHTTPMetthod{
    case GET
    case POST
}
//网络管理工具
class WBNetworkManager: AFHTTPSessionManager {
    //静态区/常量/闭包
    //在第一次访问时，执行闭包，并且将结果保存在shared常量中

    static let shared :WBNetworkManager = {
        let instance = WBNetworkManager()
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
    
    //访问令牌，所有网络请求，都基于此令牌（登录除外）
    //为了保护用户安全，TOKEN是有时限的，默认用户是三天
//    var accessToken:String?
//    
//    //用户微博ID
//    var uid:String? = "3061761015"
    lazy var userAccount = WBUserAccount()
    //用户登录标记
    var userLogon:Bool{
        return userAccount.access_token != nil
    }
    //专门负责拼接token的网络请求方法
    func tokenRequest(method:WBHTTPMetthod = .GET,URLString:String,parameters:[String:AnyObject],completion:@escaping (_ json: AnyObject?, _ isSuccess: Bool)->()){
        guard let token = userAccount.access_token else {
            print("没有token！需要登录")
            NotificationCenter.default.post(name: NSNotification.Name(rawValue:WBUserShouldLoginNotification), object: nil, userInfo: nil)
            completion(nil,false)
            return
        }
        //处理token字典
        var parameters = parameters
        if parameters == nil{
            parameters = [String:AnyObject]()
        }
        parameters["access_token"]=token as AnyObject?
        request(method: method, URLString: URLString, parameters: parameters, completion: completion)
    }
    
    func request(method:WBHTTPMetthod = .GET,URLString:String,parameters:[String:AnyObject],completion:@escaping (_ json: AnyObject?, _ isSuccess: Bool)->()) {
        let success = { (task: URLSessionDataTask, json: Any?)->() in
            
            completion(json as AnyObject?, true)
        }
        // 失败回调
        let failure = { (task: URLSessionDataTask?, error: Error)->() in
            
            //针对403处理用户token过期
            if (task?.response as? HTTPURLResponse)?.statusCode == 403{
                print("TOKEN 过期了")
                NotificationCenter.default.post(name: NSNotification.Name(rawValue:WBUserShouldLoginNotification), object: "token bad", userInfo: nil)

            }
            print("网络请求错误\(error)")
            completion(nil, false)
        }

        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    
    }
    
}
